package com.myflink.day10;

import com.myflink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

/**
 * @author Shelly An
 * @create 2020/9/27 10:48
 */
public class SQL_SQLAPI {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        //读取数据、转换
        DataStreamSource<String> socketDS = env.readTextFile("input/sensor-data.log");
        SingleOutputStreamOperator<WaterSensor> sensorDS = socketDS
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] datas = value.split(",");
                        return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                    }
                })
                .assignTimestampsAndWatermarks(
                        new BoundedOutOfOrdernessTimestampExtractor<WaterSensor>(Time.seconds(3)) {
                            @Override
                            public long extractTimestamp(WaterSensor element) {
                                return element.getTs() * 1000L;
                            }
                        }
                );

        /*---------------------------------------------------------------------------------------*/
        //1. 创建 表执行环境
//        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        EnvironmentSettings settings = EnvironmentSettings.newInstance()
                .useOldPlanner() //使用官方的planner
                //.useBlinkPlanner()    //使用blink的planner
                .inStreamingMode() //默认流 可设置批
                .build();

        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env, settings);

        //2. 把datastream转换成table  对象名是就属性名，匹配，不按顺序
        Table sensorTable = tableEnv.fromDataStream(sensorDS, "id,ts as timestamp,vc");

       //使用sql进行处理

        /*------直接用拼接对象的方式（不推荐）---------------------------------------*/
        //不能再指定字段名
        Table resultTable = tableEnv.sqlQuery("select * from " + sensorTable);
        tableEnv.toAppendStream(resultTable, Row.class).print();


        /*------用临时表的方式为表命名---------------------------------------*/
        tableEnv.createTemporaryView("sensorTable",sensorTable);
        Table reuslt1Table = tableEnv.sqlQuery("select * from sensorTable");
        tableEnv.toAppendStream(reuslt1Table, Row.class).print();

        /*------用临时表的方式为表命名 指定字段名---------------------------------------*/
        tableEnv.createTemporaryView("sensor1Table",sensorDS,"id,ts,vc");
        Table reuslt2Table = tableEnv.sqlQuery("select * from sensor1Table");
        tableEnv.toAppendStream(reuslt2Table, Row.class).print();


        env.execute();
    }
}
